<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>
<!--搜索框,可以根据用户名和密码搜索-->
<form class="layui-form" lay-filter="search" id="search" style="padding-top: 10px">
    <div class="layui-form-item">
        <!--        layui-inline,外层行内-->
        <div class="layui-inline">
            <label class="layui-form-label">商品名称</label>
            <!--            layui-input-inline,内层行内-->
            <div class="layui-input-inline">
                <input type="text" name="name" placeholder="请输入商品名称" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-inline">
            <label class="layui-form-label">发布人</label>
            <div class="layui-input-inline">
                <input type="text" name="username" placeholder="请输入发布人" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <button class="layui-btn" lay-submit lay-filter="formDemo">查询</button>
            <button type="reset" id="searchReset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>


<!--添加表单-->
<form class="layui-form" action="" style="display: none" id="addCommodity" lay-filter="editBusinessFormFilter">
    <!-- 这里设置一个隐藏域，用来存放我们的图片的地址 -->
    <input type="hidden" id="addImagePath" name="addImagePath" value="">
    <div class="layui-form-item">
        <label class="layui-form-label" name style="width: 100px">商品名称</label>
        <div class="layui-input-inline">
            <input type="text" id="addName" name="addName" required lay-verify="required" placeholder="请输入商品名称"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>


    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label" style="width: 100px">上传商品图片</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="test2">
                <i class="layui-icon">&#xe67c;</i>上传图片
            </button>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label" style="width: 100px">图片预览</label>
        <div class="layui-input-block">
            <img id="addImage" style="width: 100px;height: 100px">
        </div>
    </div>
    <div class="layui-form-item  layui-form" lay-filter="selFilter">
        <label class="layui-form-label" catgory style="width: 100px">商品类别</label>
        <div class="layui-input-inline">
            <select id="addCategoryId" lay-verify="required" name="addCategoryId">
                <option value="">请选择</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" price style="width: 100px">商品价格</label>
        <div class="layui-input-inline">
            <input type="text" id="addPrice" name="addPrice" required lay-verify="required" placeholder="请输入商品价格"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item  layui-form" lay-filter="selFilter">
        <label class="layui-form-label" catgory style="width: 100px">发布者</label>
        <div class="layui-input-inline">
            <select id="addUserId" lay-verify="required" name="addUserId">
                <option value="">请选择</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" description style="width: 100px">商品描述</label>
        <div class="layui-input-inline">
            <textarea id="addDescription" name="addDescription" placeholder="请输入该商品的描述"
                      class="layui-textarea"></textarea>
        </div>
    </div>

    <div class="layui-form-item  layui-form" lay-filter="selFilter">
        <label class="layui-form-label" catgory style="width: 100px">状态</label>
        <div class="layui-input-inline">
            <select id="addStatus" lay-verify="required" name="addStatus">
                <option value="">请选择</option>
                <option value="0">在售</option>
                <option value="1">正在交易</option>
                <option value="2">已售出</option>
                <option value="3">已下线</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="addSubmit">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<!--编辑表单-->
<form class="layui-form" action="" style="display: none" id="editCommodity" lay-filter="editBusinessFormFilter">
    <!-- 这里设置一个隐藏域，用来存放我们的图片的地址 -->
    <input type="hidden" id="imagePath" name="imagePath" value="">
    <input type="hidden" id="id" name="id" value="">
    <div class="layui-form-item">
        <label class="layui-form-label" name style="width: 100px">商品名称</label>
        <div class="layui-input-inline">
            <input type="text" id="name" name="name" required lay-verify="required" placeholder="请输入商品名称"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>


    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label" style="width: 100px">上传商品图片</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="test1">
                <i class="layui-icon">&#xe67c;</i>上传图片
            </button>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label" style="width: 100px">图片预览</label>
        <div class="layui-input-block">
            <img id="image" style="width: 100px;height: 100px">
        </div>
    </div>
    <div class="layui-form-item  layui-form" lay-filter="selFilter">
        <label class="layui-form-label" catgory style="width: 100px">商品类别</label>
        <div class="layui-input-inline">
            <select id="categoryId" lay-verify="required" name="categoryId">
                <option value="">请选择</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" price style="width: 100px">商品价格</label>
        <div class="layui-input-inline">
            <input type="text" id="price" name="price" required lay-verify="required" placeholder="请输入商品名称"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item  layui-form" lay-filter="selFilter">
        <label class="layui-form-label" catgory style="width: 100px">发布者</label>
        <div class="layui-input-inline">
            <select id="userId" lay-verify="required" name="userId">
                <option value="">请选择</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" description style="width: 100px">商品描述</label>
        <div class="layui-input-inline">
            <textarea id="description" name="description" placeholder="请输入该商品的描述" class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item  layui-form" lay-filter="selFilter">
        <label class="layui-form-label" catgory style="width: 100px">状态</label>
        <div class="layui-input-inline">
            <select id="status" lay-verify="required" name="status">
                <option value="">请选择</option>
                <option value="0">在售</option>
                <option value="1">正在交易</option>
                <option value="2">已售出</option>
                <option value="3">已下线</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="editSubmit">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<table class="layui-hide" id="test" lay-filter="demo"></table>


<script src="/layui/layui.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->
<script type="text/html" id="imgtmp">
    <img src="{{d.icon}}" style="height: 20px;height: 20px"/>
</script>
<script>
    layui.use(['table', 'jquery', 'form', 'upload'], function () {
        var table = layui.table;
        var $ = layui.$,
            form = layui.form,
            upload = layui.upload;
        //编辑表单类别下拉框
        $(function () {
            $.ajax({
                type: "get",//get或者post
                url: '/category/getAllCategory',
                data: {},//参数 接口传参 json对象
                success: function (res) {
                    console.log(res.data)
                    if (res.data) {
                        var optionHtml = '';
                        for (var i in res.data) {
                            var value1 = res.data[i]['id'];
                            var value2 = res.data[i]['cateName'];
                            optionHtml += "<option value='" + value1 + "'>" + value2 + "</option>";
                        }
                        $('#categoryId').append(optionHtml);
                        layui.form.render('select');
                    }
                }
            });
        })

        $(function () {
            $.ajax({
                type: "get",//get或者post
                url: '/user/getAllUser',
                data: {},//参数 接口传参 json对象
                success: function (res) {
                    console.log(res.data)
                    if (res.data) {
                        var optionHtml = '';
                        for (var i in res.data) {
                            var value1 = res.data[i]['id'];
                            var value2 = res.data[i]['username'];
                            optionHtml += "<option value='" + value1 + "'>" + value2 + "</option>";
                        }
                        $('#userId').append(optionHtml);
                        layui.form.render('select');
                    }
                }
            });
        })
        //添加表单类别下拉框
        $(function () {
            $.ajax({
                type: "get",//get或者post
                url: '/category/getAllCategory',
                data: {},//参数 接口传参 json对象
                success: function (res) {
                    console.log(res.data)
                    if (res.data) {
                        var optionHtml = '';
                        for (var i in res.data) {
                            var value1 = res.data[i]['id'];
                            var value2 = res.data[i]['cateName'];
                            optionHtml += "<option value='" + value1 + "'>" + value2 + "</option>";
                        }
                        $('#addCategoryId').append(optionHtml);
                        layui.form.render('select');
                    }
                }
            });
        })
        $(function () {
            $.ajax({
                type: "get",//get或者post
                url: '/user/getAllUser',
                data: {},//参数 接口传参 json对象
                success: function (res) {
                    console.log(res.data)
                    if (res.data) {
                        var optionHtml = '';
                        for (var i in res.data) {
                            var value1 = res.data[i]['id'];
                            var value2 = res.data[i]['username'];
                            optionHtml += "<option value='" + value1 + "'>" + value2 + "</option>";
                        }
                        $('#addUserId').append(optionHtml);
                        layui.form.render('select');
                    }
                }
            });
        })
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        var table_category = table.render({
            elem: '#test'
            , toolbar: '#toolbarDemo'
            , url: '/commodity/getPage'
            , cols: [
                [
                    {type: 'checkbox'}
                    , {field: 'id', width: 100, title: 'ID', sort: true, align: "center"}
                    , {field: 'name', width: 140, title: '商品名称', align: "center"}
                    , {field: 'icon', width: 100, title: '商品图片', templet: "#imgtmp", align: "center"}
                    , {field: 'categoryName', width: 100, title: '商品类别', align: "center"}
                    , {field: 'price', width: 100, title: '商品价格', sort: true, align: "center"}
                    , {field: 'username', width: 100, title: '发布者', sort: true, align: "center"}
                    , {field: 'description', width: 100, title: '商品描述', align: "center"}
                    , {
                    field: 'status', width: 100, title: '商品状态'
                    , templet: function (d) {
                        if (d.status == 0) {
                            return '<button type = "button" class="layui-btn layui-btn layui-btn-xs">在售</button>';
                        } else if (d.status == 1) {
                            return '<button type = "button" class="layui-btn layui-btn-warm layui-btn-xs">正在交易</button>';
                        } else if (d.status == 2) {
                            return '<button type = "button" class="layui-btn layui-btn-warm layui-btn-xs">已售出</button>';
                        }
                        // else {
                        //     return '<button type = "button" class="layui-btn layui-btn-danger layui-btn-xs">已下线</button>';
                        // }
                    }
                }
                    , {field: 'purchaserName', width: 100, title: '购买人', align: "center"}
                    , {field: 'right', title: '操作', toolbar: '#barDemo', width: '9%', align: 'center'}

                ]
            ]
            , page: true
            , limit: 10
            , limits: [5, 10, 15, 20, 25, 30]
        });

        //查询
        form.on('submit(formDemo)', function (data) {
            table.reload('test', {
                where: {
                    name: data.field.name,
                    username: data.field.username
                }
            });
            return false;
        });
        //监听表格复选框选择
        table.on('checkbox(demo)', function (obj) {
            console.log(obj.tr)
        });
        //监听工具条
        table.on('tool(demo)', function (obj) {
            var data = obj.data;

            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    console.log(data.id)
                    var data_t = {
                        "id": data.id,
                    };
                    $.post("/commodity/deleteCommodity",
                        {"id": data.id},
                        function (res) {
                            if (res.code == 0) {
                                layer.msg("删除成功");
                                layer.closeAll();
                                table.reload('test', {
                                        url: '/commodity/getPage',
                                        page: {
                                            curr: 1 //重新从第 1 页开始
                                        },
                                    }
                                );

                            }
                        });

                    layer.close(index);
                });
            } else if (obj.event === 'edit') {

                $("#editCommodity")[0].reset();
                layer.open({

                    type: 1,
                    title: "修改商品",
                    area: ['500px', '600x'], //宽高
                    // closeBtn: 0, //不显示关闭按钮
                    // scrollbar: false, //禁止浏览器出现滚动条
                    // resize: false, //禁止拉伸
                    // move: false, //禁止拖拽
                    // shade: 0.8, //遮罩
                    // shadeClose: true, //点击遮罩关闭当前页面
                    content: $("#editCommodity"), //这里content是一个Url
                    success: function (layero, index) {//弹出层打开后的回调函数,数据回显
                        //updateNumber为弹出层id,eaccidentNumber为数据表格的field属性
                        console.log(data);
                        $('#id').val(data.id);
                        $('#name').val(data.name);
                        $('#imagePath').val(data.icon);
                        $('#price').val(data.price);
                        // $('#category').val(data.categoryName);


                        // if(data.status == 0){
                        //     $('#status').val("在售");
                        // }else if(data.status == 1){
                        //     $('#status').val("已售出");
                        // }else if(data.status == 2){
                        //     $('#status').val("已下线");
                        // }
                        $("#categoryId").each(function () {
                            // this代表的是<option></option>，对option再进行遍历
                            $(this).children("option").each(function () {
                                // 判断需要对那个选项进行回显
                                if (this.value == data.categoryId) {
                                    console.log($(this).text());
                                    // 进行回显
                                    $(this).attr("selected", "selected");
                                }
                            });
                        });
                        $("#userId").each(function () {
                            // this代表的是<option></option>，对option再进行遍历
                            $(this).children("option").each(function () {
                                // 判断需要对那个选项进行回显
                                if (this.value == data.userId) {
                                    console.log($(this).text());
                                    // 进行回显
                                    $(this).attr("selected", "selected");
                                }
                            });
                        });
                        form.render("select");
                        $('#description').val(data.description);

                        $("#status").each(function () {
                            // this代表的是<option></option>，对option再进行遍历
                            $(this).children("option").each(function () {
                                // 判断需要对那个选项进行回显
                                if (this.value == data.status) {
                                    console.log($(this).text());
                                    // 进行回显
                                    $(this).attr("selected", "selected");
                                }
                            });
                        });
                        form.render("select");
                        $("#image").attr("src", data.icon);
                    },
                })
            }
        });
        <!--toolbar添加删除功能-->
        table.on('toolbar(demo)', function (obj) {
            var check = table.checkStatus(obj.config.id)
                , data = check.data;
            switch (obj.event) {
                case 'add':
                    $("#addCommodity")[0].reset();
                    // $("#addImagePath").val("");
                    $("#addImage").attr("src", " ");
                    layer.open({
                        title: '添加商品',
                        type: 1,
                        area: ['500px', '600px'],
                        content: $("#addCommodity")
                    });
                    break;
                case 'dels':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else {
                        var ids = [];
                        for (var i = 0; i < data.length; i++) {
                            ids[i] = data[i].id;
                        }
                        console.log(ids);
                        layer.confirm('真的删除行么', function (index) {
                            $.ajax({
                                url: '/commodity/batchDeleteCommodity',//路径
                                type: 'post',//post/get
                                data: {ids: ids},//传给后台的参数
                                dataType: 'json',//相应的数据类型,
                                success: function (result) {
                                    //成功响应函数
                                    if (result.code == 0) {
                                        layer.closeAll();
                                        table.reload('test', {
                                                url: '/commodity/getPage',
                                                page: {
                                                    curr: 1 //重新从第 1 页开始
                                                },
                                            }
                                        );
                                        layer.msg(result.msg, {icon: 6});
                                    } else {
                                        layer.msg(result.msg, {icon: 5});
                                    }
                                }
                            });
                        });
                    }
                    break;
            }
        });

        <!--图片上传-->

        //执行实例
        let uploadEdit = upload.render({
            elem: '#test1' //绑定元素
            , url: '/category/image' //上传接口
            , done: function (res) {
                if (res.code == 0) {
                    layer.msg("上传成功");
                    //获得图片的路径
                    let src = res.data.src;
                    //将图片进行回显
                    $("#image").attr("src", src);
                    //将图片的地址赋值给 form的隐藏域
                    $("#imagePath").attr("value", src);
                }
            }
            , error: function () {
                //请求异常回调
            }
        });

        //添加表单的上传图片
        let uploadAdd = upload.render({
            elem: '#test2' //绑定元素
            , url: '/commodity/image' //上传接口
            , done: function (res) {
                console.log(res.data)
                if (res.code == 0) {
                    layer.msg("上传成功");
                    //获得图片的路径
                    let src = res.data.src;
                    //将图片进行回显
                    $("#addImage").attr("src", src);
                    //将图片的地址赋值给 form的隐藏域
                    $("#addImagePath").attr("value", src);
                }
            }
            , error: function () {
                //请求异常回调
            }
        });
        //监听编辑表单的提交
        form.on('submit(editSubmit)', function (data) {
            data = data.field;
            console.log(data)
            var data_t = {
                "id": data.id,
                "name": data.name,
                "icon": data.imagePath,
                "price": data.price,
                "status": data.status,
                "categoryId": data.categoryId,
                "userId": data.userId,
                "description": data.description

            }
            //console.log(data)
            console.log(data_t)
            $.ajax({
                url: "/commodity/updateCommodity",
                method: "post",
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(data_t),
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg("修改成功");
                        layer.closeAll();
                        table_category.reload();

                    }
                }
            })
            return false;
        });
        //监听添加表单的提交
        form.on('submit(addSubmit)', function (data) {
            data = data.field;
            console.log(data);
            var data_t = {

                "name": data.addName,
                "icon": data.addImagePath,
                "price": data.addPrice,
                "status": data.addStatus,
                "categoryId": data.addCategoryId,
                "userId": data.addUserId,
                "description": data.addDescription
            }
            console.log(data_t.cateIcon)
            console.log(data_t.cateName)

            $.ajax({
                url: "/commodity/addCommodity",
                method: "post",
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(data_t),
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg("添加成功");
                        layer.closeAll();
                        table_category.reload();

                    }
                }
            })
            return false;
        });

    });
</script>

<script type="text/html" id="barDemo">
    <!--    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>-->
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="toolbarDemo">
    <!--    <a class="layui-btn layui-btn-xs" lay-event="add">添加</a>-->
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="dels">删除</a>
</script>


</body>
</html>